import logging.handlers
from os.path import dirname, abspath

# 项目根目录
BASE_DIR = dirname(dirname(abspath(__file__)))

FMT = "%(asctime)s %(levelname)s [%(filename)s %(funcName)s %(lineno)d] %(message)s"


class Logger:

    def __init__(self, filename, log_name):
        # 1. 获取一个logger对象
        self._logger = logging.getLogger(log_name)
        # 2. 设置日志等级
        self._logger.setLevel(logging.INFO)
        # 3. 设置format对象
        self.formatter = logging.Formatter(FMT)
        # 4.1 设置文件日志模式
        self._logger.addHandler(self._get_file_handler(f"{filename}"))
        # 4.2 设置终端日志模式
        self._logger.addHandler(self._get_console_handler())

    def _get_file_handler(self, filename):
        """返回一个文件日志handler"""
        # 1. 获取一个文件日志handler(提前创建一个Log文件)
        file_path = BASE_DIR + "/log/{}.log".format(filename)
        file_handler = logging.handlers.TimedRotatingFileHandler(filename=file_path,
                                                                 when="midnight",
                                                                 interval=1, backupCount=7,
                                                                 encoding="utf-8")
        # 2. 设置日志格式
        file_handler.setFormatter(self.formatter)
        # 3. 返回
        return file_handler

    def _get_console_handler(self):
        """返回一个输出到终端日志handler"""
        # 1. 获取一个输出到终端日志handler
        console_handler = logging.StreamHandler()
        # 2. 设置日志格式
        console_handler.setFormatter(self.formatter)
        # 3. 返回handler
        return console_handler

    @property
    def logger(self):
        return self._logger



if __name__ == '__main__':
    logger = Logger("cs", "cs").logger
    logger.debug("调试信息")
    logger.info("状态信息")
    logger.warning("警告信息")
    logger.error("错误信息")
    logger.critical("严重错误信息")
